<template>
  <CustomNavBar title="开票明细" />
  <view class="detail-page">
    <view v-if="detail" class="card">
      <view class="info-row">
        <text class="label">抬头名称</text>
        <text class="value">{{ safe(detail.title) }}</text>
      </view>
      <!-- <view class="divider"></view> -->

      <view class="info-row">
        <text class="label">开票类型</text>
        <text class="value">{{ typeText(detail) }}</text>
      </view>
      <!-- <view class="divider"></view> -->

      <view class="info-row">
        <text class="label">开票日期</text>
        <text class="value">{{ safe(detail.date) }}</text>
      </view>
      <!-- <view class="divider"></view> -->

      <view class="info-row">
        <text class="label">纳税人识别号</text>
        <text class="value">{{ safe(detail.taxNo) }}</text>
      </view>
      <!-- <view class="divider"></view> -->

      <view class="info-row">
        <text class="label">开票方</text>
        <text class="value">{{ safe(detail.issuer) }}</text>
      </view>
      <!-- <view class="divider"></view> -->

      <view class="info-row">
        <text class="label">发票代码</text>
        <text class="value">{{ safe(detail.invoiceCode) }}</text>
      </view>
      <!-- <view class="divider"></view> -->

      <view class="info-row">
        <text class="label">发票号码</text>
        <text class="value">{{ safe(detail.invoiceNo) }}</text>
      </view>
      <view class="divider"></view>

      <view class="info-row">
        <text class="label">合计金额</text>
        <text class="value">{{ formatCurrency(detail.amount) }}</text>
      </view>

      <view class="info-row">
        <text class="label">合计税额</text>
        <text class="value">{{ formatCurrency(detail.taxAmount) }}</text>
      </view>
      <view class="divider"></view>
    </view>
    <view v-else class="empty">
      <text>正在加载或没有数据</text>
    </view>
  </view>
</template>

<script setup>
import { ref } from 'vue';
import { onLoad } from '@dcloudio/uni-app'
import CustomNavBar from '@/components/CustomNavBar.vue'
import InvoiceApi from '@/api/app/invoice.js'

const detail = ref(null)

const typeText = (obj) => {
  if (!obj) return '—'
  // 优先使用抬头类型，其次回退到用户类型（0=商户，1=客户）
  const t = obj.type ?? obj.headerType ?? obj.titleType
  if (t !== undefined && t !== null) {
    const n = Number(t)
    if (!Number.isNaN(n)) return n === 0 ? '自然人' : '非自然人'
    const s = String(t).trim()
    if (s === '0') return '自然人'
    if (s === '1') return '非自然人'
  }
  const ut = obj.userType
  if (ut !== undefined && ut !== null) {
    const n = Number(ut)
    if (!Number.isNaN(n)) return n === 0 ? '商户' : '客户'
    const s = String(ut).trim()
    if (s === '0') return '商户'
    if (s === '1') return '客户'
  }
  return '—'
}

const safe = (v) => (v === undefined || v === null || v === '') ? '—' : v
const formatCurrency = (v) => {
  const n = Number(v)
  return isNaN(n) ? '—' : n.toFixed(2)
}

// 统一日期格式：YYYY-MM-DD HH:mm:ss，兼容数组、字符串数组、时间戳
const pad = (n) => String(n).padStart(2, '0')
const toYmdHms = (d) => {
  const y = d.getFullYear()
  const m = pad(d.getMonth() + 1)
  const day = pad(d.getDate())
  const h = pad(d.getHours())
  const mi = pad(d.getMinutes())
  const s = pad(d.getSeconds())
  return `${y}-${m}-${day} ${h}:${mi}:${s}`
}
const formatDateTime = (v) => {
  if (v === undefined || v === null || v === '') return ''
  if (typeof v === 'number') {
    const ts = v > 1e12 ? v : v * 1000
    return toYmdHms(new Date(ts))
  }
  if (Array.isArray(v)) {
    const [y, m = 1, d = 1, h = 0, mi = 0, s = 0] = v.map(Number)
    return toYmdHms(new Date(y, (m || 1) - 1, d || 1, h || 0, mi || 0, s || 0))
  }
  if (typeof v === 'string') {
    const s = v.trim()
    if (/^\d{10,13}$/.test(s)) {
      const ts = Number(s)
      return toYmdHms(new Date(s.length === 13 ? ts : ts * 1000))
    }
    const nums = s.match(/\d+/g)
    if (nums && nums.length >= 3) {
      const y = Number(nums[0])
      const m = Number(nums[1])
      const d = Number(nums[2])
      const h = Number(nums[3] ?? 0)
      const mi = Number(nums[4] ?? 0)
      const sec = Number(nums[5] ?? 0)
      return toYmdHms(new Date(y, (m || 1) - 1, d || 1, h || 0, mi || 0, sec || 0))
    }
    const parsed = new Date(s.replace(/-/g, '/').replace('T', ' '))
    if (!isNaN(parsed.getTime())) return toYmdHms(parsed)
    return s
  }
  const d = new Date(v)
  if (!isNaN(d.getTime())) return toYmdHms(d)
  return ''
}

const normalizeDetail = (raw = {}) => ({
  title: raw.title || raw.headerName || raw.headName || '',
  type: raw.type ?? raw.headerType ?? raw.titleType,
  userType: raw.userType ?? null,
  date: formatDateTime(raw.issueDate || raw.createdAt || raw.invoiceDate || raw.date || raw.createTime || ''),
  taxNo: raw.headerTaxNo || '',
  issuer: raw.issuer || raw.sellerName || '听鸽共享充电桩',
  invoiceCode: raw.invoiceCode || raw.code || '',
  invoiceNo: raw.invoiceNo || raw.number || raw.invoiceNumber || '',
  amount: raw.amount ?? raw.totalAmount ?? raw.price ?? '',
  taxAmount: raw.taxAmount ?? '',
  // 兼容字段，便于后续联动
  userId: raw.userId ?? null,
  pendingId: raw.pendingId ?? null,
  headerId: raw.headerId ?? null,
  invoiceUrl: raw.invoiceUrl ?? '',
  invoiceIdUrl: raw.invoiceIdUrl ?? '',
  invoiceStatus: raw.invoiceStatus ?? null
})

onLoad(async (options) => {
  const id = options?.id
  if (!id) {
    // 缺少ID，不加载假数据，提示并返回
    uni.showToast({ title: '缺少ID', icon: 'none' })
    return
  }

  uni.showLoading({ title: '加载中', mask: true })
  try {
    const res = await InvoiceApi.getInvoiceHistoryDetail({ id })
    // 接口兼容 res 或 res.data 结构
    const raw = (res && typeof res === 'object') ? (res.data ?? res) : {}
    detail.value = normalizeDetail(raw)
  } catch (e) {
    console.error('获取发票历史明细失败', e)
    // 不再注入示例假数据，仅提示错误
    uni.showToast({ title: '加载失败', icon: 'none' })
  } finally {
    uni.hideLoading()
  }
})
</script>

<style scoped>
.detail-page {
  min-height: 100vh;
  background-color: #fff;
}
.card {
  padding: 0 30rpx;
}
.info-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 24rpx 0;
}
.label {
  font-size: 28rpx;
  color: #7A7A7C;
}
.value {
  flex: 1;
  text-align: right;
  font-size: 32rpx;
  /* color: #333; */
}
.divider {
  height: 1px;
  background-color: #DCDFEC;
  margin-right: -30rpx;
}
.empty {
  padding: 200rpx 30rpx 0;
  text-align: center;
  color: #7A7A7C;
}
</style>